<?
/**
 * VoiceOne Settings/Extensions/edit
 *
 * Frontend to provide access to the extensions system in voiceone.
 * @package voiceone
 * @subpackage  settings_extensions
 * @todo Remove hardcoded italian message for confirmation box (AlertGood. AlertBad etc)
 */
 
  include ("../../../admin/config/cfg.php");
  global $cwlang,$cwUserInfo,$cwUserId;
  require_once("$absBasePath/lib/xajax/xajax.inc.php"); 
  
  //================ XAJAX ================
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath,$cwUserId;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    //extract form params
    $group=$formData["contactGroup"];
    $id=$group["id"];
    $name=$group["name"];
    $entity=$group["entity"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
    //get groups
    $groupnameArr=array();
    $ret=$asterisk->getContactGroup(0,$cwUserId);
    if(is_array($ret)){
      foreach($ret as $g){
        if($id==$g["id"]) continue;
        $groupnameArr[]=$g["name"];
      }
    }
    // Check group name ((not null)&&(unique))
    $nameErr=false;
    if(trim($name)==""){
      //name must be not null
      $errOut[]=T_("Name must be not null");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }else if((is_array($groupnameArr))&&(in_array($name,$groupnameArr,true))){
      //name must be unique
      $errOut[]=T_("Group already exists. Please change it");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }
    if($nameErr===false) $objResponse->addAssign("nameErr","innerHTML","");
    // Check entity list (not empty)
    /*
    $entityErr=false;
    if(trim($entity)==""){
      //entity list must be not empty
      $errOut[]=$cwlang["phonebook"]["gentityNotNull"];
      $objResponse->addAssign("entityErr","innerHTML",$imgErr);
      $entityErr=true;
    }
    if($entityErr===false) $objResponse->addAssign("entityErr","innerHTML","");
    */
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML","");
      $script=" document.getElementById('mainform').submit(); ";
      $objResponse->addScript($script);
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();  
  }
  function getList($search){
    global $asterisk,$cwlang,$relBasePath,$cwUserId;
    DEFINE("CONTACTS_IN_LIST", 100);
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Create contact list
  	$opt="";
    $ret=$asterisk->getContactList($cwUserId,"",$search,CONTACTS_IN_LIST,1);
    if(!is_array($ret)){
    	$opt.="<option value=\"0\" disabled=\"disabled\">".T_("[search didn't match any contacts]")."</option>";
      $toomuchAlert="&nbsp;";
    }else{
    	if(count($ret)>99) $toomuchAlert=T_("(*) First 100 search results"); 
      else $toomuchAlert="&nbsp;";
      foreach($ret as $v){
        $id=$v["id"];
        $id_user=$v["id_user"];
        if(strlen($v["name"])>25) $name=substr($v["name"],0,25)."..."; else $name=$v["name"];
        $write=$v["write"];        
        $opt.="<option value=\"".$id."\">".$name."</option>";
      }
    }
  	// Return the xajaxResponse object
    $opt="<select id=\"c_select\" size=\"10\" multiple=\"multiple\">".$opt."</select>";
    $objResponse->addAssign("c_list","innerHTML",$opt);
    $objResponse->addAssign("toomuch","innerHTML",$toomuchAlert);
    return $objResponse->getXML();  
  }
  $xajax = new xajax();
  $xajax->registerFunction("processFormData");
  $xajax->registerFunction("getList");
  $xajax->processRequests();
  //================== POST ====================
  if(count($_POST)>0){
    $contactGroup=$_POST["contactGroup"];
    $entry=Array(
          "id" => $contactGroup["id"],
          "name" => $contactGroup["name"],
          "entity" => $contactGroup["entity"]
        );
    //put Contact 
    $ret=$asterisk->putContactGroup($entry,$cwUserId);
    if($ret>0) $alert="<div class=\"AlertGood\">".T_("Group of contacts successfully saved")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Edit Group failed")."</div>";
	  //go to main page
    goToMainPage($alert);
  }
  //================ PAGE LOGIC ================
  //Get the client informations
  if(isset($_GET["id"]) and $_GET["id"]!=""){
    $ret=$asterisk->getContactGroup($_GET["id"],$cwUserId);
    if(!is_array($ret)) die;
    $g=$ret[0];
    $id=$g["id"];
    $name=$g["name"];
    $entityArr=$g["entity"];
    //title
    $title=sprintf(T_("Modify Groups of Contacts &lt; %s &gt;"),$name );
  }else{
	  //title
    $title=T_("New Groups of Contacts");
  }
  //set group's contacts
  $opt="";
  if(is_array($entityArr)){
  	$c_num_value=count($entityArr);
  	foreach($entityArr as $e){
    	$ret=$asterisk->getContact($e,$cwUserId);
      if((is_array($ret))&&(is_array($ret[0]))){
      	$arr=$ret[0];
      	if($arr["order_field"]=="name"){
        	if(trim($arr["company"])!="") $c_name=$arr["name"]." ".$arr["surname"]." (".$arr["company"].")";
          else $c_name=$arr["name"]." ".$arr["surname"];
        }else if($arr["order_field"]=="company"){
        	if((trim($arr["surname"])!="")||(trim($arr["name"])!="")) $c_name=$arr["company"]." (".$arr["surname"]." ".$arr["name"].")";
          else $c_name=$arr["company"];
        }else{
        	if(trim($arr["company"])!="") $c_name=$arr["surname"]." ".$arr["name"]." (".$arr["company"].")";
          else $c_name=$arr["surname"]." ".$arr["name"];
        }
        if(strlen($c_name)>25) $c_name=substr($c_name,0,25)."...";
      	$opt.="<option value=\"".$arr["id"]."\">".$c_name."</option>";
      }
    }
  }else $c_num_value=0;
  $c_num_visual="(".$c_num_value.")";
  //init script
  $init_script="<script> xajax_getList(''); </script>";
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../admin/lib/xajax/"); ?>
  <?=$init_script?>
  <div class="SectionHeader">
    <h1><?=$title?></h1>
    <h3><a href="../" class="admin" ><?=T_("Return without save")?></a></h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?>" method="post">
      <!-- General Info -->
      <h2><?=T_("General Informations")?></h2>
      <p class="blockintro"><?=T_("Group's general informations")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="contactGroup[name]"><?=T_("Name")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="255" id="contactGroup[name]" name="contactGroup[name]" value="<?=$name?>" /><span id="nameErr"></span></dd>
        </dl>
      </div>
      <!-- Entities -->
      <h2><?=T_("Contacts group")?></h2>
      <p class="blockintro"><?=T_("Choose the contacts that belongs to this group")?></p>
      <div class="block">
      	<div style="width:100%; overflow:hidden;">
        	<!-- All Contact List -->
        	<div style="float:left;padding:10px 0 10px 30px;">
          	<div style="height:30px;">
            	<input type="text" style="vertical-align:middle;" id="search" name="search" size="23" value="" onkeyup="if(event.keyCode==13){document.getElementById('c_list').innerHTML='<select size=\'10\'></select><div style=\'display:inline;\'><img style=\'vertical-align:top;padding-left:5px;\' src=\'<?=$relBasePath?>public/img/ico-progress.gif\'/><span style=\'vertical-align:top;\'>&nbsp;<?=T_("loading")?>...</span></div>';xajax_getList(document.getElementById('search').value);} return false;" />
            	<input type="image" style="vertical-align:top;cursor:pointer;" src="<?=$relBasePath?>/public/img/search.gif" alt="Search" onclick="document.getElementById('c_list').innerHTML='<select size=\'10\'></select><div style=\'display:inline;\'><img style=\'vertical-align:top;padding-left:5px;\' src=\'<?=$relBasePath?>public/img/ico-progress.gif\'/><span style=\'vertical-align:top;\'>&nbsp;<?=T_("loading")?>...</span></div>';xajax_getList(document.getElementById('search').value);return false;"/>
            </div>
            <div id="toomuch" style="line-height:20px;color:#666;margin:0;padding:0;border:0;">&nbsp;</div>
            <div id="c_list">
          		<select size="10"></select>
            	<div style="display:inline;"><img style="vertical-align:top;" src="<?=$relBasePath?>public/img/ico-progress.gif"/><span style="vertical-align:top;">&nbsp;<?=T_("loading")?>...</span></div>
            </div>
            <div style="text-align:center;padding-top:5px;">
            	<img style='vertical-align:top;' src='<?=$relBasePath?>public/img/unknown.gif'/>
            	<a href="" onclick="document.getElementById('search').value='';document.getElementById('c_list').innerHTML='<select size=\'10\'></select><div style=\'display:inline;\'><img style=\'vertical-align:top;padding-left:5px;\' src=\'<?=$relBasePath?>public/img/ico-progress.gif\'/><span style=\'vertical-align:top;\'>&nbsp;<?=T_("loading")?>...</span></div>';xajax_getList('');return false;"><?=T_("reset search")?></a>
            </div>
          </div>
          <!-- Add Buttons -->
          <div style="float:left;padding:110px 30px 0 30px;width:80px;">
          	<input type="button" onclick="add()" value="<?=T_("&nbsp;&nbsp;&nbsp;Add&nbsp;&nbsp;&nbsp;>&nbsp;")?>"/>
          	<input type="button" onclick="addAll()" value="<?=T_("Add All >>")?>"/>
          </div>
          <!-- Group's Contact List -->
          <div style="float:left;padding-top:40px;">
          	<div id="c_num_visual" style="line-height:20px;color:#666;margin:0;padding:0;border:0;"><?=$c_num_visual?></div>
          	<select name="contactGroup[entity][]" id="g_select" size="10" multiple="multiple"><?=$opt?></select>
            <div style="text-align:center;padding-top:5px;">
            	<img style='vertical-align:top;' src='<?=$relBasePath?>public/img/trash.gif'/>
              <a href="" onclick="remove();return false;"><?=T_("remove selected")?></a>
            </div>
          </div>  
          <input id="c_num_value" type="hidden" value="<?=$c_num_value?>" />
        </div>
      </div>
      <!-- Buttons -->
      <div class="action">
        <?if ($_GET["id"]!="") {?> <input type="hidden" id="contactGroup[id]" name="contactGroup[id]" value="<?=$id?>" /> <?}?>
        <a href=""><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" document.getElementById('alert').innerHTML=''; selectContacts(); xajax_processFormData(xajax.getFormValues('mainform'));"/></a>
      </div>
    </form> 
  </div> 
  
  <script type="text/javascript">
    function addAll(){
      	fromSelect=document.getElementById('c_select');
        for(var i=0; i<fromSelect.length; i++){
        	optObj=fromSelect.options[i];
        	if(optObj.disabled==false) optObj.selected=true;
        }
        add();
      }
      function add(){
      	var skip=false;
      	fromSelect=document.getElementById('c_select');
        toSelect=document.getElementById('g_select');
        for(var i=0; i<fromSelect.length; i++){
        	num=parseInt(document.getElementById('c_num_value').value)+1;
        	optObj=fromSelect.options[i];
          if((optObj.selected==true)&&(optObj.disabled==false)){
          	//check if option already exists
          	skip=false;
            for(var j=0; j<toSelect.length; j++){
        			if(toSelect.options[j].value==optObj.value) skip=true;
            }
            if(skip==true) continue;
            //create new option
          	var newOptObj=document.createElement('option');
            newOptObj.value=optObj.value;
            newOptObj.text=optObj.text;
            //add new option
            try {
      				toSelect.add(newOptObj,null); // standards compliant; doesn't work in IE
            }
            catch(ex) {
              toSelect.add(newOptObj); // IE only
            }
            //refresh contact count
            document.getElementById('c_num_value').value=num;
            document.getElementById('c_num_visual').innerHTML='('+ num +')';
          }
        }
      }
    function remove(){
    	fromSelect=document.getElementById('g_select');
      var redo=true;
      while(redo){
        redo=false;
        for(var i=0; i<fromSelect.length; i++){
        	optObj=fromSelect.options[i];
          if(optObj.selected==true){
          	fromSelect.remove(i);
            //refresh contact count
          	num=parseInt(document.getElementById('c_num_value').value)-1;
          	document.getElementById('c_num_value').value=num;
          	document.getElementById('c_num_visual').innerHTML='('+ num +')';
            redo=true;
            break;
          }
        }
      }
    }
    function selectContacts(){
    	fromSelect=document.getElementById('g_select');
      for(var i=0; i<fromSelect.length; i++){
      	fromSelect.options[i].selected=true;
      }
    }
  </script>
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <?$sel="groups";include("../../sidebar.php");?>
      <h1><?=T_("Informations")?></h1>
      <p><?=T_("To be done...")?></p>
      <div style="text-align: center"><img src="<?=$relBasePath?>public/img/book.jpg" alt="Rubrica" align="center"/></div>
    </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
  $smarty->assign("section", "contacts");
  $smarty->assign("subsection", "");
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('main.tpl');
  
  /*
  //build html for external contacts (extensions)
  $alphabet=array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","#");
  //group contacts in tab
  $tabArr=array();
  $ret=$asterisk->getContact(0,$cwUserId);
  if (is_array($ret)){
    foreach($ret as $v) {
      $cid=$v["id"];
      $gname=$v["name"];
      $gsurname=$v["surname"];
      $gcompany=$v["company"];
      if(trim($gsurname)!="") $tab=strtolower(substr(trim($gsurname),0,1));
      else if(trim($gcompany)!="") $tab=strtolower(substr(trim($gcompany),0,1));
      else if(trim($gname)!="") $tab=strtolower(substr(trim($gname),0,1)); 
      else $tab="#";
      $tabArr[$tab][]=$v;
    }
  }  
  $html_tabs="";
  $html_ext="";
  $div_num=1;
  foreach($alphabet as $key){
    $alfgroup=$tabArr[$key];
    if(is_array($alfgroup)) $class="act"; else $class="dis";
    $html_tabs.="<li><a href=\"#fragment-".$div_num."\"  style=\"background-image: url(".$relBasePath."public/img/tab.png);\"><span class=\"$class\" style=\"background-image: url(".$relBasePath."public/img/tab.png);\">".strtoupper($key)."</span></a></li>\n";
    $html_ext.="<div id=\"fragment-".$div_num."\">\n";
    if(is_array($alfgroup)){
      $count=0;
      $html_ext.="<table width=\"100%\"><tr>";
      foreach($alfgroup as $contact){
        $cname=$contact["name"];
        $csubname=$contact["surname"];
        $ccompany=$contact["company"];
        $cphonenumber=$contact["phonenumber"];
        $cmobile=$contact["mobile"];
        if((is_array($entityArr))&&(@in_array($contact["id"], $entityArr))) $chk="checked='checked'"; else $chk="";
        if(($cwUserId!=$contact["id_user"])&&($cwUserInfo["type"]==USER_STANDARD)&&($contact["write"]!=1)) $disabled="disabled=\"disabled\""; else $disabled="";
        $class="unknown";
        $icon="<img src=\"".$relBasePath."public/img/$class.gif\" alt=\"Contact Groups\" />";
        //logic
        $alt="";
        if(trim($v["phonenumber"])!="") $alt.=$v["phonenumber"]." | ";
        if(trim($v["mobile"])!="") $alt.=$v["mobile"]." | ";
        if($alt!="") $alt=substr($alt,0,-3);
        //label
        $rif=$csurname;
        if(trim($cname)!="") $rif.=" ".$cname;
        if(trim($ccompany)!=""){
          if(trim($rif)!="") $rif.=" (".$ccompany.")";
          else $rif=$ccompany;
        }
        if((trim($cphonenumber)!="")&&(trim($rif)=="")) $rif=$cphonenumber;
        if((trim($cmobile)!="")&&(trim($rif)=="")) $rif=$cmobile;  
        //html
        $html_ext.="<td style=\"font-size: xx-small;\"> <input type=\"checkbox\" name=\"contactGroup[entity][]\" value=\"".$contact["id"]."\" $chk $disabled/> $icon $rif</td>\n";
        if((++$count)%2==0) $html_ext.="</tr><tr>\n";
      }
      if(($count!=0)&&(($count%2)!=0)) $html_ext.="<td colspan=\"".($count%2)."\">&nbsp;</td>\n";
      $html_ext.="</tr></table>";
    }else{
      $html_ext.="<p style=\"text-align:center;\">".$cwlang["phonebook"]["letterNoContacts"]." ".strtoupper($key)."</p>";
    }
    $html_ext.="</div>\n";
    $div_num++;
  }
  //html ext
  $html_ext="<ul>".$html_tabs."</ul>".$html_ext;
  */
?>

